﻿using EntityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore.ChangeTracking;

namespace API.Controllers
{
    [Route("yjh/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly HallDbContext _Db;
        public UserController(HallDbContext _context)
        {
            _Db = _context;
        }

        [HttpGet]
        public List<User> GetUsers()
        {
            return _Db.User.ToList();
        }
        //[HttpGet]
        //返回单个字段
        //public string? GetUsers()
        //{
        //    //where 条件
        //    //selec 查询表中的字段
        //    return _Db.User.Where(w => w.FirstName == "张").Select(s => s.FirstName).FirstOrDefault();
        //}

        //public Result GetAllUser()
        //{
        //    var UserName= _Db.User.Where(w => w.FirstName == "张").Select(s => new{
        //        s.FirstName,
        //        s.LastName
        //    }). FirstOrDefault();
        //    Result result = new Result();
        //    result.Data = UserName;
        //    return result;
        //}

        /// <summary>
        /// 带参数的查询
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("{Id}")]
        public Result Get(Guid Id)
        {
            User? UserName = _Db.User.Where(w => w.Id == Id).FirstOrDefault();
            Result result = new Result();
            if (UserName == null)
            {
                result.Code = 404;
            }
            else
            {
                result.Code = 200;
                result.Data = UserName;
            }
            return result;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public Result AddUser([FromBody]User user)
        {
            Result result = new Result();
            _Db.User.Add(user);
            _Db.SaveChanges();
            return result;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public Result DelUser(Guid id)
        {
            Result result = new Result();
            User? user = _Db.User.Where(s=>s.Id==id).SingleOrDefault();
            if (user != null)
                _Db.User.Remove(user);
            result.Data = _Db.SaveChanges();
            return result;
        }

        /// <summary>
        /// 更改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPut]
        public Result UpUser([FromBody]User user)
        {
            Result result = new Result();
            _Db.User.Update(user);
            result.Data = _Db.SaveChanges();
            return result;
        }
    }
}
